﻿using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.VersionControl.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TeamExplorer.Merge.Base;

namespace TeamExplorer.Merge.MergeCandidates
{
    public class WorkspaceViewModel : NotifyPropertyChangedBase
    {
        private VersionControlServer vcs;
        private Workspace _currentWorkspace;

        public WorkspaceViewModel(VersionControlServer vcs)
        {
            this.vcs = vcs;
            _currentWorkspace = TryGetWorkspace();
        }

        internal Workspace TryGetWorkspace()
        {
            if (vcs == null)
                return (Workspace)null;
            Workspace workspace = (Workspace)null;
            try
            {
                if (workspace == null)
                    workspace = GetPendingChangesWorkspace();
                if (workspace == null)
                    workspace = GetSCEWorkspace();
            }
            catch (Exception)
            {
                workspace = (Workspace)null;
            }
            return workspace;
        }

        /// <summary>
        /// get from pending changes registry key
        /// </summary>
        /// <returns></returns>
        private Workspace GetPendingChangesWorkspace()
        {
            Workspace current = VersionControlSettings.Instance.GetLastWorkspaceForServer(vcs, VersionControlSettings.LastWorkspaceSource.PendingCheckins);
            return current;
        }

        /// <summary>
        /// get from source control explorer registry key
        /// </summary>
        /// <returns></returns>
        private Workspace GetSCEWorkspace()
        {
            Workspace current = VersionControlSettings.Instance.GetLastWorkspaceForServer(vcs, VersionControlSettings.LastWorkspaceSource.Explorer);
            return current;
        }

        public Workspace CurrentWorkspace
        {
            get { return _currentWorkspace; }
            set
            {
                if (value == _currentWorkspace) { return; }

                _currentWorkspace = value;
                RaisePropertyChanged("CurrentWorkspace");
                RaisePropertyChanged("CurrentWorkspaceName");
            }
        }
        
        public string CurrentWorkspaceName 
        {
            get { return (CurrentWorkspace != null) ? CurrentWorkspace.Name : null; }
        }
    }
}
